package com.bicntech.system.service;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.bicntech.common.constant.Constants;
import com.bicntech.common.core.domain.entity.SysUser;
import com.bicntech.common.core.domain.model.LoginUser;
import com.bicntech.common.core.service.LogininforService;
import com.bicntech.common.enums.DeviceType;
import com.bicntech.common.enums.UserStatus;
import com.bicntech.common.exception.user.CaptchaException;
import com.bicntech.common.exception.user.CaptchaExpireException;
import com.bicntech.common.exception.user.UserException;
import com.bicntech.common.helper.LoginHelper;
import com.bicntech.common.utils.ServletUtils;
import com.bicntech.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 登录校验方法
 *
 * @author Lion Li
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysLoginService {
    private static final ThreadLocal<Map<String, String>> KEY_CACHE = new ThreadLocal<>();
    private final ISysConfigService configService;
    private final ISysUserService userService;
    private final SysPermissionService permissionService;
    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        HttpServletRequest request = ServletUtils.getRequest();
//        boolean captchOnOff = configService.selectCaptchaOnOff();
//        if (captchOnOff) {
//            validateCaptcha(username, code, uuid, request);
//        }
        SysUser user = loadUserByUsername(username);
        LoginUser loginUser = buildLoginUser(user);
        System.out.println(StpUtil.getTokenInfo());
        // 生成token
        LoginHelper.loginByDevice(loginUser, DeviceType.PC);
        return StpUtil.getTokenValue();
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     */
    public void validateCaptcha(String username, String code, String uuid, HttpServletRequest request) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + StringUtils.defaultString(uuid, "");
        var redis = KEY_CACHE.get();
        String captch = redis.get(verifyKey);
        if (captch == null) {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captch)) {
            throw new CaptchaException();
        }
    }

    private SysUser loadUserByUsername(String username) {
        SysUser user = userService.selectUserByUserName(username);
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UserException("user.not.exists", username);
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new UserException("user.password.delete", username);
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new UserException("user.blocked", username);
        }
        return user;
    }

    private LoginUser buildLoginUser(SysUser user){
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getUserId());
        loginUser.setDeptId(user.getDeptId());
        loginUser.setUsername(user.getUserName());
        loginUser.setUserType(user.getUserType());
        loginUser.setMenuPermission(permissionService.getMenuPermission(user));
        return loginUser;
    }

}
